package com.chucang.shucang.common.security.service;

import com.chucang.shucang.common.base.constant.CacheConstant;
import com.chucang.shucang.common.base.constant.CommonConstant;
import com.chucang.shucang.common.base.constant.SecurityConstant;
import com.chucang.shucang.common.base.utils.R;
import com.chucang.shucang.common.security.feign.vo.AppUserInfo;
import com.chucang.shucang.common.security.entity.ShuCangUser;
import com.chucang.shucang.common.security.feign.AppUserDetailService;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;

/**
 * @author flitsneak
 * @email flitsneak@gmail.com
 * @date 2022/9/17 17:03
 * @description app短信模式登录
 */
@Slf4j
@RequiredArgsConstructor
public class ShuCangAppSmsUserDetailsServiceImpl implements ShuCangUserDetailsService {
    private final AppUserDetailService appUserDetailService;

    private final CacheManager cacheManager;

    /**
     * 手机号登录
     *
     * @param cellPhoneNum 手机号
     * @return 用户信息
     */
    @Override
    @SneakyThrows
    public UserDetails loadUserByUsername(String cellPhoneNum) {
        Cache cache = cacheManager.getCache(CacheConstant.USER_DETAILS);
        if (cache != null && cache.get(cellPhoneNum) != null) {
            return (ShuCangUser) cache.get(cellPhoneNum).get();
        }

        R<AppUserInfo> result = appUserDetailService.getUserInfoByCellPhone(cellPhoneNum, SecurityConstant.FROM_IN);

        AppUserInfo userInfo = result.getData();
        if (cache != null) {
            cache.put(cellPhoneNum, new ShuCangUser(userInfo.getId(), userInfo.getCellPhoneNum(), SecurityConstant.BCRYPT + userInfo.getPassword(), userInfo.getCellPhoneNum(), userInfo.getUsername(), userInfo.getIsRealAuth(), userInfo.getOffshoreAccount(), userInfo.getStatus() == CommonConstant.STATUS_NORMAL, true, true, true, AuthorityUtils.NO_AUTHORITIES));
        }
        return new ShuCangUser(userInfo.getId(), userInfo.getCellPhoneNum(), SecurityConstant.BCRYPT + userInfo.getPassword(), userInfo.getCellPhoneNum(), userInfo.getUsername(), userInfo.getIsRealAuth(), userInfo.getOffshoreAccount(), userInfo.getStatus() == CommonConstant.STATUS_NORMAL, true, true, true, AuthorityUtils.NO_AUTHORITIES);
    }

    /**
     * check-token 使用
     *
     * @param shuCangUser
     * @return
     */
    @Override
    public UserDetails loadUserByUser(ShuCangUser shuCangUser) {
        return this.loadUserByUsername(shuCangUser.getCellPhoneNum());
    }

    /**
     * 是否支持此客户端校验
     *
     * @param clientId 目标客户端
     * @return true/false
     */
    @Override
    public boolean support(String clientId, String grantType) {
        return SecurityConstant.APP_SMS.equals(clientId);
    }
}
